#!/usr/bin/env python3
"""
从环境变量初始化超级管理员
"""
import sys
import os
import uuid

# 将项目根目录添加到 Python 路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from app.core.database import SessionLocal
from app.core.config import settings
from app.models.user import User
from app.core.security import hash_password

def init_super_admin():
    """从环境变量初始化超级管理员"""
    db = SessionLocal()
    
    try:
        phone = settings.SUPER_ADMIN_PHONE
        password = settings.SUPER_ADMIN_PASSWORD
        nick_name = settings.SUPER_ADMIN_NICKNAME
        
        print("\n" + "=" * 50)
        print("  初始化超级管理员")
        print("=" * 50)
        print(f"\n配置信息（来自 .env 文件）:")
        print(f"  手机号: {phone}")
        print(f"  昵称: {nick_name}")
        print(f"  密码: {'*' * len(password)}")
        
        # 检查是否已存在
        existing_user = db.query(User).filter(User.phone == phone).first()
        
        if existing_user:
            print(f"\n⚠️  用户已存在: {existing_user.nick_name} ({existing_user.phone})")
            
            if existing_user.role == "super_admin":
                print("✅ 该用户已经是超级管理员")
            else:
                print(f"   当前角色: {existing_user.role}")
                # 升级为超级管理员
                existing_user.role = "super_admin"
                existing_user.password_hash = hash_password(password)
                existing_user.nick_name = nick_name
                db.commit()
                print("✅ 已升级为超级管理员并更新密码")
        else:
            # 创建新的超级管理员
            admin = User(
                id=str(uuid.uuid4()),  # 生成 UUID
                phone=phone,
                password_hash=hash_password(password),
                nick_name=nick_name,
                role="super_admin",
                avatar="https://minio.aqilmini.com/football/default-avatar.png"
            )
            
            db.add(admin)
            db.commit()
            db.refresh(admin)
            
            print("\n✅ 超级管理员创建成功！")
            print(f"\n账号信息：")
            print(f"  ID: {admin.id}")
            print(f"  手机号: {admin.phone}")
            print(f"  昵称: {admin.nick_name}")
            print(f"  角色: {admin.role}")
        
        print("\n" + "=" * 50)
        print("  完成！")
        print("=" * 50)
        print(f"\n登录管理后台: http://your-domain/admin")
        print(f"账号: {phone}")
        print(f"密码: [在 .env 文件中配置的密码]")
        print()
        
    except Exception as e:
        db.rollback()
        print(f"\n❌ 初始化失败: {str(e)}")
        import traceback
        traceback.print_exc()
    finally:
        db.close()

if __name__ == "__main__":
    init_super_admin()

